package util;

import java.lang.reflect.Array;

import entities.Entity;

public class EntityList {

	private static final Object[] EMPTY_LIST = new Object[0];

	private Object[] entityList;

	public EntityList() {
		entityList = EMPTY_LIST;
	}

	public <T extends Entity> void add(Class<T> t, T entity) {
		int oldLength;
		Object[] newEntityList;

		if (entity == null)
			return;

		if (!t.isInstance(entity))
			throw new IllegalArgumentException();

		oldLength = entityList.length;
		newEntityList = new Object[oldLength + 2];

		if (oldLength > 0)
			System.arraycopy(entityList, 0, newEntityList, 0, oldLength);

		newEntityList[oldLength] = t;
		newEntityList[oldLength + 1] = entity;
	}

	@SuppressWarnings("unchecked")
	public <T extends Entity> T[] getEntities(Class<T> t, boolean allowSubclassses) {
		Entity[] results = (Entity[]) Array.newInstance(t, getEntityCount());
		int arrayCounter = 0;
		for (int i = 0; i < entityList.length; i += 2) {
			if (entityList[i] == t || (allowSubclassses && t.isInstance(entityList[i + 1]))) {
				results[arrayCounter] = (Entity) entityList[i + 1];
				arrayCounter++;
			}
		}
		return (T[]) results;
	}

	public Entity[] getEntityList() {
		return (Entity[]) entityList;
	}
	
	private int getEntityCount() {
		return entityList.length / 2;
	}
}
